package com.hxt.util;

import java.io.FileInputStream;
import java.net.URL;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.ClassPathResource;
import org.yaml.snakeyaml.Yaml;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;

public class ResourceUtil {

	public static String getOSSPath() {

		String bucketName = getKey("bucketName");
		String endPoint = getKey("endpoint");
		StringBuffer sb = new StringBuffer();
		sb.append("http://").append(bucketName).append(".").append(endPoint).append("/");
		return sb.toString();

	}

	/**
	 * 拼装OSS路径
	 * 
	 * @param src
	 * @return
	 */
	public static String getOssString(String src) {

		if (StringUtils.isNotBlank(src)) {
			StringBuffer sb = new StringBuffer();
			return sb.append(getOSSPath()).append(src).toString();
		}
		return "";
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static Map<String, String> getYmlMap() {
		Map<String, String> map = Maps.newHashMap();
		try {
			Yaml yaml = new Yaml();
			URL url = ResourceUtil.class.getClassLoader().getResource("application.yml");
			if (url != null) {
				return (Map) yaml.load(new FileInputStream(url.getFile()));
				// 通过map我们取值就可以了.
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;

	}

	public static String getKey(String key) {
		String value = getYmlMap().get(key);
		return value;
	}

	/**
	 * 获取yml
	 * 
	 * @return
	 */
	public static String readYaml() {
		Map<String, String> map = Maps.newHashMap();
		try {
			Yaml yaml = new Yaml();
			URL url = ResourceUtil.class.getClassLoader().getResource("application.yml");
			if (url != null) {
				return yaml.dump(yaml.load(new FileInputStream(url.getFile())));

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}

	/**
	 * 获取资源文件
	 * 
	 * @param path为src/main/resources目录下文件
	 * @return 返回字符
	 */
	public static String getResourceFileAsString(String path) {
		try {

			return IOUtils.toString(new ClassPathResource(path).getInputStream(), "utf8");

		} catch (Exception e1) {
			e1.printStackTrace();
		}
		return null;
	}

	/**
	 * 获取资源文件
	 * 
	 * @param path为src/main/resources目录下文件
	 * @return 返回JSON对象
	 */
	public static JSONObject getResourceFileAsJsonObject(String path) {
		try {
			return JSONObject.parseObject(getResourceFileAsString(path));
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		return null;
	}
}
